<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>授权管理</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<link rel="stylesheet" href="../css/mui.min.css">
		<link rel="stylesheet" href="../css/common.css" />
		<link rel="stylesheet" type="text/css" href="../css/mui.picker.min.css" />
		<style type="text/css">
			#buildingMode{
				width: 100%;
				height: 100%;
				position: absolute;
				left: 0;
				top: 44px;	
				background-color: #fff;
				overflow-y: scroll;
				z-index: 9990;
			}
			#personUl{
				background=color: #fff!important;
			}
			#chooseBox ul li{
				position: relative;
			}
			#chooseBox ul li .mui-icon-plus{
	    	position: absolute;
	    	right: 1rem;
	    	top: .9rem;
	    	color: #2B8DF7;
	    	font-size: 1.6rem;
	    	z-index: 99;
	    	font-weight: bold;
	    	}
	    	 #cardBox dl{
	    	 	position: relative;
	    	 }
		    #cardBox .delBtn{
				width: 15px;
				height: 15px;
				position: absolute;
				right: -5px;
				top: -7px;
				background-color: orangered;
				color: #fff;
				border-radius: 100%;
				border: none;
				font-size: .2rem;
				line-height:15px;
		    }
		</style>
	</head>
	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left" id="firBack"></a>
			<h1 class="mui-title">授权管理</h1>
		</header>
	
		<div class="mui-content" id="muiContent">
			<section id="chooseBox">
				<ul class="item-flashing">
					<li class="item-weight newView" id="buildingBtn"><label for="">房屋</label><input readonly="readonly" type="text" id="building" placeholder="请选择房屋"/></li>
					<li class="item-weight" id="chooseTime"><label for="">结束时间</label><input readonly="readonly" id="endTime" type="text" placeholder="请选择结束时间"/></li>
				</ul>
				<div style="background-color: #F0F0F0;height: .4rem;"></div>
				<ul class="item-flashing">
					<li class="item-weight newView" id="chooseUser"><label for="">姓名</label>
						<input readonly="readonly" type="text" id="personNameInput" placeholder="选择 / 新增人员"/>
					</li>
					<li class="item-weight"><label for="">身份证</label>
						<input type="text" readonly="readonly" id="personIdNumInput" placeholder="请选择身份证"/>
						<span class="mui-icon mui-icon-plus" id="readIdInfomation"></span>
					</li>
				</ul>
				<div style="background-color: #F0F0F0;height: .4rem;"></div>
				<div class="addCard">
					<p>授权卡</p>
					<div class="item-flashing" style="margin: .5rem 0;" id="addCard">
						<div class="card-box mui-clearfix" id="cardBox">
							<dl id="addCarddBtn">
								<dd class="dd-img">+</dd>
								<dd>新增卡</dd>
							</dl>
						</div>
						
					</div>
				</div>
				<div style="background-color: #F0F0F0;height: .4rem;"></div>
				<ul class="item-flashing">
					<li class="item-weight">
						<label for="">APP开门</label>
						<div class="mui-switch mui-active" id="authoritionSwitch">
  							<div class="mui-switch-handle"></div>
						</div>
					</li>
				</ul>
			</section>
			<div class="btn-box">
				<button type="button" class="mui-btn mui-btn-primary" id="createCard">完成</button>
			</div>
			
		</div>
		
		<!--房屋模板-->
		<div id="buildingMode" class="mui-popover mui-popover-action">
			<div class="scrollDiv">
				<div class="search-li">
			    	<div class="search-box">
					    <input type="search" id="house_serch_input" placeholder="请输入楼栋相关信息">
						<button type="button" id="house_serch">查询</button>
			    	</div>
				</div>
				<div class="houst-list">
					<ul id="house_ul">
						
					</ul>
				</div>
			</div>
		</div>
		<!--房屋模板-->
		<!--楼栋，房屋列表的模板-->
		<div class="mui-popover mui-popover-action" id="personMode">
			<div class="search-li">
		    	<div class="search-box">
				    <input type="search" id="person_serch_input" placeholder="请输入人员相关信息">
					<button type="button" id="person_serch">查询</button>
		    	</div>
			</div>
			<!--<div class="personHouseAddress">
				<p id="Address"></p>
			</div>-->
			<div class="person-list">
				<ul id="house_ul">
					
				</ul>
			</div>
		</div>	
		
	<script src="../js/jquery.js"></script>
	<script src="../js/mui.min.js"></script>
	<script src="../js/app.js"></script>
	<script src="../js/mui.picker.min.js"></script>
	<script src="../js/md5.js"></script>
	<script>
	
	mui.init({
		swipeBack:true, //启用右滑关闭功能,
		longtap:true
	});
	
	var mobileNum = getUrlMobile('mobile');
	localStorage.setItem('mobile',mobileNum);
	//房屋弹层：
	document.getElementById('buildingBtn').addEventListener('tap',function(){
		mui('#buildingMode').popover('toggle');
		var house_li = document.getElementById('house_ul').getElementsByTagName('li');
		if(house_li.length>0){//如果已经请求了，就不再请求，只是显示与隐藏而已
			return;
		}else{
			initPage_building('','');//默认传空值
		}
	})
	
	
	//选择房屋
	function initPage_building(q_word,o_cond){
		var q_word = q_word;
		var o_cond = o_cond;
		var mobile = localStorage.getItem('mobile');//本地取到电话号码
		var timestamp = formatDateTime();//年月日时分秒
		var key = 'udacs!@#';//固定的key值
		var token = mobile + timestamp + key;//token的拼接
		var md5 = hex_md5(token);//token的ma5加密
		//获取楼栋list
		$.ajax(httpUrl+'get_house_list',{
			data:JSON.stringify({
				"auth":{
					"mobile":mobile,
					"token":md5,
					"imei":"imei",
					"imsi":"imsi",
					"timestamp" :timestamp
				},
		   		"api_ver":"1",
				"req":{
					"mobile":mobile ,
					"q_word":q_word ,
					"o_cond":o_cond,
//					"building_id":
					"page":"1",
					"type":"1"
				}
			}),
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			contentType: "text/plain; charset=utf-8",					
			success:function(data){
				var resp =JSON.stringify(data.resp)
				var res = JSON.parse(resp);
				var houseList = document.getElementById('house_ul');
				houseList.innerHTML = '';//清空数据
				mui.each(res,function(ind,item) {
					houseList.insertAdjacentHTML('beforeEnd','<li class="houseLi"  data-houseId="'+item.id+'" data-houseName="'+item.name+'"><span class="icon-house"></span><span class="house-name">'+item.name+'</span></li>');
				});
			},
			error:function(xhr,type,errorThrown){
				mui.toast('网络异常或者服务器出错：'+type,{duration:'short',type:''});
			}
				
		})
	}


	
	initPage_building('','')
	//选择楼栋
	mui('#house_ul').on('tap','li',function(){
		var houseId = this.getAttribute('data-houseId');
		localStorage.setItem('houseId',houseId);
		document.getElementById('building').value = this.getElementsByTagName('span')[1].innerText;
		mui('#buildingMode').popover('toggle');
	})
	//楼栋查询
	document.getElementById('house_serch').addEventListener('tap',function(){
		var house_serch_input = document.getElementById("house_serch_input").value;
		console.log(house_serch_input);
		initPage_building(house_serch_input,'');//传关键字
	})
	
	//结束时间
	document.getElementById('chooseTime').addEventListener('tap',function(){
		var dtpicker = new mui.DtPicker({
		    type: "datetime",//设置日历初始视图模式 
		    beginDate: new Date().getFullYear(),//设置开始日期 
		    endDate: new Date(2099, 12, 31),//设置结束日期 
		    labels: ['年', '月', '日', '时', '分'],//设置默认标签区域提示语 
		    customData: { 
		       
		    }//时间/日期别名 
		}) 
		
		dtpicker.show(function(endTime_record) {
		    document.getElementById('endTime').value = endTime_record.value//.slice(0,10);
		}) 
	})
	//姓名
	document.getElementById("personNameInput").addEventListener('tap',function(houseId){
		var buildingInfo = {
				buildingName : document.getElementById('building').value,
				endTime : document.getElementById('endTime').value
			}
		localStorage.setItem('buildingInfo',JSON.stringify(buildingInfo));
		location.href = 'chooseHouse.html';
		
	})

	//调取摄像头扫描身份证。
	document.getElementById('readIdInfomation').addEventListener('tap',function(){
		window.android.scanIdCard();
	})
	//原生调取的方法把扫描身份证的信息传回来。
	function getInfoMation(res){
		if(res){
			document.getElementById("personNameInput").value = res.name;
			document.getElementById('personIdNumInput').value = res.id;
			// document.getElementById('nationPiker').value = res.nation;
			// document.getElementById('birthDay').value = res.birth;
			// document.getElementById("p_address").value = res.address;
			//性别处理
			// var person_sex = ''
			// if(res.sex=='男'){
			// 	person_sex= '0'
			// }else if(res.sex=='女'){
			// 	person_sex= '1'
			// }
			// $("input[name='sex']").removeAttr('checked');
			// $("input[name='sex']").each(function(){
			// 	if($(this).attr('data-sex')==person_sex){
			// 		$(this).attr('checked',true);
				// }
			// });
		}else{
			alert('解析信息有误，请重新操作！')
		}
	}
	//添加卡片
	document.getElementById("addCarddBtn").addEventListener('tap',function(){
		 
		if(document.getElementById('building').value!==''){
			if(localStorage.getItem('carUUID')){
				location.href = 'addCard.html';
			}else{//第一次进来
				var carUUID = [];
				localStorage.setItem('carUUID',JSON.stringify(carUUID));
				location.href = 'addCard.html';
			}
			
		}else{
			mui.toast('请先选择房屋！',{duration:'short',type:''})
		}
		
	});
	//删除卡号
	function delCard(_this){
		var inde = parseInt(_this.getAttribute('data-index'));
		$($('.delBtn')[inde]).parent().remove();//删除结构
		var carUUID = JSON.parse(localStorage.getItem('carUUID'));//取到存储的数据
		for(var i = 0;i<carUUID.length;i++){
			if(i==inde){
				console.log(i,inde)
				carUUID.splice(inde,1);//对数据进行操作，并更新存储的数据
				break;
			}
		}
		localStorage.setItem('carUUID',JSON.stringify(carUUID));
	}
	
	//人员信息，由于是本地存储，进来先获取地址栏的相应标识，如果没有hasLocalStorage为空，是第一次进来，把本地存储清掉
	var hasLocalStorage = getUrlMobile('hasLocalStorage');//获取地址标识
	if(hasLocalStorage==null){
		localStorage.removeItem('personInfo');//清掉本地存储
		localStorage.removeItem('buildingInfo');
		localStorage.removeItem('carUUID');
	}else{
		//如果是人员页面返回来，就本数据渲染在页面上
		if(localStorage.getItem('buildingInfo')){
			var buildingInfo = JSON.parse(localStorage.getItem('buildingInfo'));
			document.getElementById('building').value = buildingInfo.buildingName;
			document.getElementById('endTime').value = buildingInfo.endTime;
		}
		
		if(localStorage.getItem('personInfo')){
			var personInfo = JSON.parse(localStorage.getItem('personInfo'));
			document.getElementById("personNameInput").value = personInfo.personName;
			document.getElementById("personIdNumInput").value = personInfo.personidNum;
		}
		if(localStorage.getItem('carUUID')){
			var cardInfo = JSON.parse(localStorage.getItem('carUUID'));
			var addCarddBtn = document.getElementById("addCarddBtn");
			for(var i = 0;i<cardInfo.length;i++){
				addCarddBtn.insertAdjacentHTML('beforeBegin','<dl class="cardHandle"><dd class="dd-img"></dd><dd class="card">'+cardInfo[i]+'</dd><dd class="delBtn" onclick="delCard(this)" data-index="'+i+'">x</dd></dl>')
			}
		}
		
	}
	
	document.getElementById('createCard').addEventListener('tap',function(){
		var mobile = localStorage.getItem('mobile');//本地取到电话号码（即登录的房东号码）
		var houseName = document.getElementById('building').value;//楼栋名称
		var houseId = localStorage.getItem('houseId');//楼栋id
		var personMobile = JSON.parse(localStorage.getItem('personInfo')).person_user_mobile;
		var starttime = document.getElementById('endTime').value;//结束时间
		    starttime =starttime+':00';
	    	starttime = starttime.replace(new RegExp("-","gm"),"/");
	    var houseEndTime = (new Date(starttime)).getTime(); //得到毫秒数
		var authoritionSwitch = document.getElementById('authoritionSwitch');
		var isAuthorition = 1;//默认app开门
		var carUUID = [];//添加的卡的数组
		var cardNum = document.getElementById('cardBox').getElementsByClassName('card');
		for(var i=0;i<cardNum.length;i++){
			carUUID[i] = {};
			carUUID[i].uuid = cardNum[i].innerText;
		}
		if(authoritionSwitch.classList.contains('mui-active')==false){
			isAuthorition = 0;//手动关闭默认app开门
		}
		var timestamp = formatDateTime();//年月日时分秒
		var key = 'udacs!@#';//固定的key值
		var token = mobile + timestamp + key;//token的拼接
		var md5 = hex_md5(token);//token的ma5加密
		var currentTIme = new Date().getTime();
		if(mobile&&houseId&&houseEndTime&&personMobile&&(carUUID.length>0||isAuthorition==1)){
	    		$.ajax(httpUrl+'app_accredit',{
					data:JSON.stringify({
						"auth":{
							"mobile":mobile,
							"token":md5,
							"imei":"imei",
							"imsi":"imsi",
							"timestamp" :timestamp
						},
				   		"api_ver":"1",
						"req":{
							"mobile": mobile,
					        "house_id":houseId,
					        "house_end_time": houseEndTime,
					        "user_id": personMobile,
					        "card_list": carUUID,
					        "app_open": isAuthorition,
							"charge_time":currentTIme,
						}
					}),
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					contentType: "text/plain; charset=utf-8",					
					success:function(data){
						if(data.rsmsg.rscode=="0"){
							mui.toast(data.rsmsg.rsdesc,{duration:'short',type:''})
							setTimeout(function () {
	    		 	    		//跳转到首页
	    		 	    		window.android.finish();
							}, 1500)
						}else if(data.rsmsg.rscode=="1"){
							mui.toast(data.rsmsg.rsdesc,{duration:'short',type:''});
						}	
			},
			error:function(xhr,type,errorThrown){
				mui.toast('网络异常或者服务器出错：'+type,{duration:'short',type:''});
			}
		})
	}else{
		mui.toast('填写完才能提交哦！',{duration:'short',type:''});
	}
	
   
	})	
	
	//第一层页面自定义返回按钮操作
	document.getElementById("firBack").addEventListener('tap',function(){
		window.android.finish();
	})
</script>

    </body>
</html>